package com.hph.demo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * 聊天室客户端
 * @author 10499
 */
public class NettyChatClientDemo {

    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new MySocketChannelHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();
            System.out.println("客户端已启动！！！");
            Channel socketChannel = channelFuture.channel();
            Scanner scanner = new Scanner(System.in);
            while(scanner.hasNext()) {
                String msg = scanner.next();
                if("quit".equals(msg)) {
                    socketChannel.close();
                    break;
                }
                socketChannel.write(msg);
                socketChannel.flush();
            }
            channelFuture.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }

    static class MySocketChannelHandler extends SimpleChannelInboundHandler<String> {


        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {

            System.out.println("您已上线！！！");
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {

            System.out.println("您已下线！！！");
        }

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {

            System.out.println(s);
        }
    }
}
